local blaze = require "blaze"
local app = require "app"
local game = app.game.running
local consts = game.util.consts

local M = game.ui.element()

local log = game.logging.get("Seat")

M.store_watchers = {
    gameplay = {
        ["$"] = blaze.noop,

        ["玩家下注"] = function(self, store, state, args)
            local player = args.player
            if self.player == player then
                self.animator:Play("seat_bet_clip")    
            end
        end,

        ["筹码变更"] = function(self, store, state, args)
            local player = args.player
            if self.player ~= player then
                return
            end

            if state.phase_id == consts.PHASE_PAYOUT then
                -- 赔付阶段等赔付动画结束后再刷新
                return
            end

            local old = args.old
            local current = args.current
            self:update_chip(old, current)
        end
    }    
}

function M:ctor(no, res)
    self.res = "club.threecard.baccaratlib/ui/common.b:seat" or res

    self.player = nil
    self.no = no

    local AvatarIcon = require "ui.Common.AvatarIcon"
    self.avatar_icon = AvatarIcon.new()
end

function M:on_load()
    self:super("on_load")

    self.avatar_icon:load()
    self.avatar_icon:set_parent(self.head_root, false)
end

function M:on_injected(bind)
    bind("app.event", "赔付动画结束", self.on_payout_ani_completed)
end

function M:set_data(player)
    self.player = player
    self:lazy("on_set_data")
end

function M:mark_luck(b)
    self.is_luck = b
    self:lazy('on_mark_luck')
end

function M:on_mark_luck()
    self.luck_flag:SetActive(self.is_luck)
end

function M:mark_rich(index)
    self.rich_index = index
    self:lazy('on_mark_rich')
end

function M:on_mark_rich()
    self.rich_flag:SetActive(self.rich_index == 1)
end

function M:on_set_data()
    if not self.player then
        self.root.gameObject:SetActive(false)
        self.empty_root.gameObject:SetActive(true)
        return
    end

    self.root.gameObject:SetActive(true)
    self.empty_root.gameObject:SetActive(false)

    local player = self.player
    self.avatar_icon:set_head(player.head)
    self.name_txt.text = player.name
    local old = nil
    local current = player.chip
    self:update_chip(old, current)
end

function M:update_chip(old, current)
    game.utility.digit(self.chip_txt, old, current, game.i18n.styles.chip2)
end

function M:on_payout_ani_completed(e)
    if e.no ~= self.no then
        return
    end
    self:update_chip(self.player.chip - e.amount, self.player.chip)
end

return M